<script setup>
  // import { onLoad } from '@dcloudio/uni-app'
  import { getList, markReaded } from '@/apis/message'
  import { ref, onMounted } from 'vue'
  import { toast } from '@/utils/utils'

  const list = ref([]) // 列表数据
  const pages = ref(0) // 总页码
  const page = ref(1) // 当前页码

  const loadData = async () => {
    const res = await getList({
      contentType: 201,
      page: page.value,
      pageSize: 5,
    })
    // 要追加，不能直接赋值替换
    list.value.push(...(res.data.items || []))
    pages.value = res.data.pages
  }

  onMounted(() => {
    loadData()

    // 监听详情页触发这个获取详情的事件
    uni.$on('__message_content_get_detail', (id) => {
      const item = list.value.find((v) => v.id === id)

      // 改为已读
      item.isRead = 1

      // TODO: 发请求更新已读状态

      // 发送详情
      uni.$emit('__message_send_detail', item)
    })
  })

  const onScrollToLower = () => {
    if (page.value >= pages.value) return toast('没有更多了')
    page.value++
    loadData()
  }

  const refreshing = ref(false)
  const onRefresh = async () => {
    refreshing.value = true
    // 刷新：重新加载第一页的数据，将现有的数据清空
    page.value = 1
    list.value = []
    try {
      await loadData()
    } finally {
      refreshing.value = false
    }
  }

  const goDetail = (detail) => {
    if (detail.isRead === 0) {
      detail.isRead = 1
      markReaded(detail.id)
    }

    uni.setStorageSync('__message_detail', detail)

    uni.navigateTo({
      url: '/subpkg_message/content/index',
    })
  }
</script>
<template>
  <scroll-view
    class="scroll-view"
    refresher-enabled
    scroll-y
    :refresher-triggered="refreshing"
    @scrolltolower="onScrollToLower"
    @refresherrefresh="onRefresh"
  >
    <view class="scroll-view-wrapper">
      <view class="message-action">
        <text class="iconfont icon-clear"></text>
        全部已读
      </view>
      <uni-card v-for="v of list" :key="v.id" :border="false" :is-shadow="false">
        <view class="brief">{{ v.content }}</view>
        <view class="extra">
          <text class="time">{{ v.created }}</text>
          <!-- <navigator hover-class="none" class="link" :url="`/subpkg_message/content/index?id=${v.id}`"
            >查看详情</navigator
          > -->
          <text class="link" @click="goDetail(v)">查看详情</text>
        </view>
        <template v-slot:title>
          <view class="title" :class="{ unread: v.isRead === 0 }">{{ v.title }}</view>
        </template>
      </uni-card>
      <view v-if="list.length === 0" class="message-blank">暂无消息</view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
